package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.itheima.pojo.BlogSort;
import com.itheima.service.BlogService;
import com.itheima.service.BlogSortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/classify")
public class ClassifyController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private BlogSortService blogSortService;

    /**
     * 通过blogSortUid获取文章
     * @param blogSortUid
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/getArticleByBlogSortUid")
    public Map<String,Object> getArticleByBlogSortUid(@RequestParam("blogSortUid") String blogSortUid, @RequestParam(name = "currentPage",defaultValue = "1",required = false) Integer currentPage, @RequestParam(name = "pageSize",defaultValue = "10",required = false) Integer pageSize){

        //获取blogSort对象
        BlogSort blogSort = blogSortService.findBlogByUid(blogSortUid);
        //根据blogSortUid获取相应的blogList
        PageInfo pageInfo = blogService.getBlogListBySortUid(blogSortUid, currentPage, pageSize);
        //封装返回结果
        List list = pageInfo.getList();
        List<Map> records=new ArrayList<>();
        for (Object o : list) {
            //将blog对象转化为map
            Map map = JSON.parseObject(JSON.toJSONString(o), Map.class);
            map.put("blogSort",blogSort);
            records.add(map);
        }
        Map<String,Object> result=new HashMap<>();
        result.put("code","SUCCESS");

        Map<String,Object> data=new HashMap<>();
        data.put("records",records);
        data.put("total",pageInfo.getTotal());
        data.put("size",pageInfo.getSize());
        data.put("current",pageInfo.getPageNum());
        data.put("orders",new ArrayList<>());
        data.put("optimizeCountSql",true);
        data.put("isSearchCount",true);
        //将将data放入返回map
        result.put("data",data);

        return result;
    }

    /**
     * 获取分类的信息
     * @return
     */
    @GetMapping("/getBlogSortList")
    public Map<String,Object> getBlogSortList(){
        List<BlogSort> blogSortList = blogSortService.getAllBlogSort();
        //封装返回数据
        Map<String,Object> result=new HashMap<>();
        result.put("code","SUCCESS");
        result.put("data",blogSortList);
        return result;
    }
}
